<?php

namespace App\Http\Controllers\Admin;

use App\Services\WxCard\WxCardService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * 微信卡券控制器
 * @package App\Http\Controllers\Admin
 */
class WxCardController extends BaseWxController
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 卡券列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request, WxCardService $wxCardSer)
    {
        if ($request->ajax()) {
            $pageSize = $request->get('pageSize', 10);
            $query = \App\Models\WxCardBase::select('*');
            //当前选择微信应用数据
            $curWxMp = \Auth::user()->getWxMpCurrent();
            $appid = $curWxMp ? $curWxMp['appid'] : '';
            $query->where('appid', $appid);
            //卡券类型
            $cardType = $request->get('card_type', '');
            if (!empty($cardType)){
                $query->where('card_type', $cardType);
            }
            //搜索关键字
            $keyword = $request->get('keyword', '');
            if ($keyword) {
                $query->where('title', 'like', '%' . $keyword . '%');
            }
            $data = $query->orderBy('card_base_id', 'DESC')->paginate($pageSize);
            $data = !empty($data) ? $data->toArray() : [];
            if ($data['data']) {
                $cardList = $data['data'];
                foreach ($cardList as $k => $v) {
                    $v['card_type_str'] = $this->wxCardSer->getTypeNameStr($v['card_type']);
                    $v['audit_status_str'] = $this->wxCardSer->getCardStatusStr($v['audit_status']);
                    $cardList[$k] = $v;
                }
                $data['data'] = $cardList;
            }
            return $data;
        }
        //卡券类型列表
        $cardTypeList = $wxCardSer->getTypeNameList();
        $this->viewData['cardTypeList'] = $cardTypeList;
        return view('admin.wxcard.index', $this->viewData);
    }

    /**
     * 设置测试白名单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function upsetTestWhite(Request $request, WxCardService $wxCardSer)
    {
        if ($request->ajax()) {
            if ($request->isMethod('GET')) {
                try {
                    $whiteList = $wxCardSer->getTestWhitelist();
                    return $this->showMsg('success', '获取测试白名单成功', ['openIds' => $whiteList], 'admin.wxcard.index');
                } catch (\Exception $e) {
                    return $this->showMsg('error', $e->getMessage());
                }
            }
            if ($request->isMethod('POST')) {
                try {
                    $openIds = $request->post('openIds', []);
                    $wxCardSer->setTestWhitelist($openIds);
                    return $this->showMsg('success', '设置测试白名单成功', [], 'admin.wxcard.index');
                } catch (\Exception $e) {
                    return $this->showMsg('error', $e->getMessage());
                }
            }
        }
    }

    /**
     * 添加、编辑展示页
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function form(Request $request, WxCardService $wxCardSer)
    {
        $cardBaseId = $request->get('id', 0);
        $cardData = [];
        if ($cardBaseId) {
            //当前选择微信应用数据
            $curWxMp = \Auth::user()->getWxMpCurrent();
            $appid = $curWxMp ? $curWxMp['appid'] : '';
            $base = \App\Models\WxCardBase::with(['advance', 'member', 'ext'])->where('appid', $appid)->findOrFail($cardBaseId);
            $cardData['base'] = $base->toArray();
            //print_r($cardData['base']);exit();
            if (!empty($cardData['base']['advance'])) {
                $cardData['advance'] = $cardData['base']['advance'];
                unset($cardData['base']['advance']);
            }
            //会员卡信息
            if (!empty($cardData['base']['member'])) {
                $cardData['member'] = $cardData['base']['member'];
                unset($cardData['base']['member']);
            }
            //卡券扩展字段（）
            if (!empty($cardData['base']['ext'])) {
                $cardData['ext'] = $cardData['base']['ext'];
                unset($cardData['base']['ext']);
            }
        }
        if (empty($cardData['base'])) {
            $cardData['base'] = [
                'card_id' => '',
                'card_key' => '',
                'card_type' => '', 'title' => '', 'code_type' => '',
                'sku' => ['quantity' => 0],
                'date_info' => [
                    'type' => 'DATE_TYPE_FIX_TIME_RANGE',
                    'begin_timestamp' => null, 'end_timestamp' => null, 'fixed_term' => null, 'fixed_begin_term' => 0,
                ],
                'bind_openid' => 0,
                'use_all_locations' => 0,
                'use_custom_code' => 0,
                'get_custom_code_mode' => '',
                'center_info' => ['center_title' => '', 'center_sub_title' => '', 'center_url' => '', 'center_app_brand_user_name' => '', 'center_app_brand_pass' => ''],
                'custom_info' => ['custom_url_name' => '', 'custom_url_sub_title' => '', 'custom_url' => '', 'custom _app_brand_user_name' => '', 'custom_app_brand_pass' => ''],
                'promotion_info' => ['promotion_url_name' => '', 'promotion_url_sub_title' => '', 'promotion_url' => '', 'promotion_app_brand_user_name' => '', 'promotion_app_brand_pass' => ''],
                'get_limit' => 0,
                'use_limit' => 0,
                'can_share' => 0,
                'can_give_friend' => 0,
            ];
        }
        if (empty($cardData['advance'])) {
            $cardData['advance'] = [
                'use_condition' => ['islimit' => 0, 'accept_category' => '', 'reject_category' => '', 'least_cost' => 0, 'object_use_for' => '', 'can_use_with_other_discount' => 1,],
                'abstract' => ['abstract' => '', 'icon_url_list' => [0 => ''],],
                'text_image_list' => [],
                'time_limit' => [
                    ['type' => 'MONDAY', 'isopen' => 0, 'name' => '周一', 'begin_hour' => null, 'begin_minute' => null, 'end_hour' => null, 'end_minute' => null],
                    ['type' => 'TUESDAY', 'isopen' => 0, 'name' => '周二', 'begin_hour' => null, 'begin_minute' => null, 'end_hour' => null, 'end_minute' => null],
                    ['type' => 'WEDNESDAY', 'isopen' => 0, 'name' => '周三', 'begin_hour' => null, 'begin_minute' => null, 'end_hour' => null, 'end_minute' => null],
                    ['type' => 'THURSDAY', 'isopen' => 0, 'name' => '周四', 'begin_hour' => null, 'begin_minute' => null, 'end_hour' => null, 'end_minute' => null],
                    ['type' => 'FRIDAY', 'isopen' => 0, 'name' => '周五', 'begin_hour' => null, 'begin_minute' => null, 'end_hour' => null, 'end_minute' => null],
                    ['type' => 'SATURDAY', 'isopen' => 0, 'name' => '周六', 'begin_hour' => null, 'begin_minute' => null, 'end_hour' => null, 'end_minute' => null],
                    ['type' => 'SUNDAY', 'isopen' => 0, 'name' => '周日', 'begin_hour' => null, 'begin_minute' => null, 'end_hour' => null, 'end_minute' => null],
                ],
                'business_service' => [],
                'share_friends' => 0,
            ];
        }
        if (empty($cardData['ext'])) {
            $cardData['ext'] = [
                'least_cost' => 0,
                'reduce_cost' => 0,
                'discount' => 0,
                'deal_detail' => '',
                'gift' => '',
                'default_detail' => '',
            ];
        }
        if (empty($cardData['member'])) {
            $cardData['member'] = [
                'activate' => [
                    'type' => 'onekey',
                    'field_list' => [
                        ['type' => 'USER_FORM_INFO_FLAG_MOBILE', 'name' => '手机号', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                        ['type' => 'USER_FORM_INFO_FLAG_SEX', 'name' => '性别', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                        ['type' => 'USER_FORM_INFO_FLAG_NAME', 'name' => '姓名', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                        ['type' => 'USER_FORM_INFO_FLAG_BIRTHDAY', 'name' => '生日', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                        ['type' => 'USER_FORM_INFO_FLAG_IDCARD', 'name' => '身份证', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                        ['type' => 'USER_FORM_INFO_FLAG_EMAIL', 'name' => '邮箱', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                        ['type' => 'USER_FORM_INFO_FLAG_LOCATION', 'name' => '详细地址', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                        ['type' => 'USER_FORM_INFO_FLAG_EDUCATION_BACKGROUND', 'name' => '教育背景', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                        ['type' => 'USER_FORM_INFO_FLAG_INDUSTRY', 'name' => '行业', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                        ['type' => 'USER_FORM_INFO_FLAG_INCOME', 'name' => '收入', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                        ['type' => 'USER_FORM_INFO_FLAG_HABIT', 'name' => '兴趣爱好', 'is_common' => 1, 'is_open' => 0, 'is_required' => 0,],
                    ],
                    'activate_url' => '', 'activate_app_brand_user_name' => '', 'activate_app_brand_pass' => '', 'activate_begin_time' => '', 'activate_end_time' => '',
                    'init_bonus' => 0, 'init_bonus_record' => '',
                    'init_balance' => 0, 'init_custom_field_value1' => '', 'init_custom_field_value2' => '', 'init_custom_field_value3' => '',
                    'auto_activate' => 0, 'wx_activate' => 1, 'wx_activate_after_submit' => 0, 'wx_activate_after_submit_url' => '',
                    'required_form_can_modify' => 0,
                    'optional_form_can_modify' => 0,
                ],
                'service_statement' => ['name' => '', 'url' => ''],//服务声明
                'bind_old_card' => ['name' => '', 'url' => ''],//绑定老会员链接
                'bonus' => ['supply_bonus' => 0, 'bonus_cleared' => '', 'bonus_rules' => ''],
                'balance' => ['supply_balance' => 0, 'balance_url' => '', 'balance_rules' => ''],
                'custom_field1' => ['isopen' => 0, 'name_type' => '', 'name' => '', 'url' => ''],
                'custom_field2' => ['isopen' => 0, 'name_type' => '', 'name' => '', 'url' => ''],
                'custom_field3' => ['isopen' => 0, 'name_type' => '', 'name' => '', 'url' => ''],
                'custom_cell1' => ['isopen' => 0, 'name' => '', 'tips' => '', 'url' => ''],
                'custom_cell2' => ['isopen' => 0, 'name' => '', 'tips' => '', 'url' => ''],
                'custom_cell3' => ['isopen' => 0, 'name' => '', 'tips' => '', 'url' => ''],
                'bonus_rule' => [
                    'cost_money_unit' => 0, 'increase_bonus' => 0, 'max_increase_bonus' => 0, 'init_increase_bonus' => 0, 'cost_bonus_unit' => 0, 'reduce_money' => 0, 'least_money_to_use_bonus' => 0, 'max_reduce_bonus' => 0
                ],
                'discount' => 0,
            ];
        }
        $this->viewData['cardData'] = $cardData;
        //卡券类型列表
        $cardTypeList = $wxCardSer->getTypeNameList();
        $this->viewData['cardTypeList'] = $cardTypeList;
        //卡券标识分组列表
        $this->viewData['cardKeyGroupList'] = $wxCardSer->getCardKeyGroupList();
        //码型列表
        $codeTypeList = $wxCardSer->getCodeTypeList();
        $this->viewData['codeTypeList'] = $codeTypeList;
        //颜色列表
        $colorList = $wxCardSer->getColors();
        $this->viewData['colorList'] = $colorList;
        //有效期时间类型
        $dateTypeList = $wxCardSer->getDateTypeList();
        $this->viewData['dateTypeList'] = $dateTypeList;
        return view('admin.wxcard.form', $this->viewData);
    }

    /**
     * 保存卡券
     * @param \App\Http\Requests\AdminWxCardPost $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function save(\App\Http\Requests\AdminWxCardPost $request, WxCardService $wxCardSer)
    {
        try {
            $cardId = $request->input('base.card_base_id', 0);
            $cardType = $request->input('base.card_type', '');
            $rs = $wxCardSer->createCardObj($cardType)->save($request);
            if ($rs) {
                return $this->showMsg('success', ($cardId ? '编辑' : '添加') . '卡券成功', [], 'admin.wxcard.index');
            }
            throw new \Exception(($cardId ? '编辑' : '添加') . '卡券失败');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }

    /**
     * 删除卡券
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function destroy(Request $request, WxCardService $wxCardSer)
    {
        try {
            $cardBaseId = $request->input('card_base_id', 0);
            $rs = $wxCardSer->destory($cardBaseId);
            if ($rs) {
                return $this->showMsg('success', '删除卡券成功', [], 'admin.wxcard.index');
            }
            throw new \Exception('删除卡券失败');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }

    /**
     * 卡券发布
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function publish(Request $request, WxCardService $wxCardSer)
    {
        try {
            $cardBaseId = $request->input('card_base_id', 0);
            $cardType = $request->input('card_type', '');
            $rs = $wxCardSer->createCardObj($cardType)->publish($cardBaseId);
            if ($rs) {
                return $this->showMsg('success', '发布卡券成功', [], 'admin.wxcard.index');
            }
            throw new \Exception('发布卡券失败');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }

    /**
     * 同步卡券
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function sync(Request $request)
    {
        try {
            //当前选择微信应用数据
            $curWxMp = \Auth::user()->getWxMpCurrent();
            $appid = $curWxMp ? $curWxMp['appid'] : '';

            \App\Jobs\WxCardSync::dispatch($appid)->onQueue('default');
            return $this->showMsg('success', '执行同步成功', [], 'admin.wxcard.index');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }
    /**
     * 修改卡券库存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function modifyStock(Request $request, WxCardService $wxCardSer)
    {
        try {
            $cardBaseId = $request->input('card_base_id', 0);
            $stockNum = $request->input('stock_num', 0);
            $modType = $request->input('mod_type', 'increase');
            $rs = $wxCardSer->modifyStock($cardBaseId, $stockNum, $modType);
            if ($rs) {
                return $this->showMsg('success', '修改卡券库存成功', [], 'admin.wxcard.index');
            }
            throw new \Exception('修改卡券库存失败');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }
}
